package ce.com.cenewbluesdk.ota.ota_modea;

import android.util.Log;


import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

import ce.com.cenewbluesdk.uitl.CRC16;


public class OtaUtil {
    /**
     * @param devVersion
     * @return key为type, value为versionCode
     */
    public static Map<Integer, Integer> versionStr2Map(String devVersion) {
        Map<Integer, Integer> map = new HashMap<>();
        String itemVersion[] = devVersion.split("\\.");
//        otaLog("Version=" + devVersion);
        for (int i = 0; i < itemVersion.length; i++) {
            map.put(i + 1, Integer.valueOf(itemVersion[i]));
//            DealOtaFile.otaLog("Integer.valueOf(itemVersion[i])=" + Integer.valueOf(itemVersion[i]));
        }
        return map;
    }

    public static boolean equalVersionMap(Map<Integer, Integer> oldVersionMap, Map<Integer, Integer> newVersionMap) {
        if (oldVersionMap.size() != newVersionMap.size()) {
            return false;
        }
        for (Integer key : oldVersionMap.keySet()) {
            if (!oldVersionMap.get(key).equals(newVersionMap.get(key))) {
                return false;
            }
        }
        return true;
    }

    /**
     * 获得指定文件的byte数组
     */
    public static byte[] getBytes(String filePath) {
        byte[] buffer = null;
        try {
            File file = new File(filePath);
            FileInputStream fis = new FileInputStream(file);
            ByteArrayOutputStream bos = new ByteArrayOutputStream(1000);
            byte[] b = new byte[1000];
            int n;
            while ((n = fis.read(b)) != -1) {
                bos.write(b, 0, n);
            }
            fis.close();
            bos.close();
            buffer = bos.toByteArray();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // TODO: 2016/2/2 抛异常时流没关闭
        return buffer;
    }

    public static boolean checkCrc16OK(int crc, byte b[]) {
        if (crc == CRC16.crc16(b)) {
            return true;
        }
        return false;
    }

    public static String otaLog(String s) {
        Log.e("otak6 ", s);
        return s;
    }
}
